from fastapi import APIRouter, HTTPException
from models.models import Student,Course
from pydantic import BaseModel,field_validator
from datetime import datetime

# from fastapi.exceptions import HTTPException

router = APIRouter()

@router.get("/")
async def get_students():
    # # (1) 查询所有 all()方法
    # students = await Student.all() # QuerySet: [Student(),Student(),Student()]
    # print(students[0].name)
    #  # 获取第一个学生的名称
    # for student in students:
    #     print(student.name)

    # # (2) 过滤查询 filter()方法
    # students_filter = await Student.filter(classes_id=1) # QuerySet: [Student(),Student(),Student()]
    # print(students_filter[0].name)

    # # (3) 过滤查询 get()方法：返回的是一个模型类对象
    # one_student = await Student.get(name="曾宪俊") # Student()
    # print(one_student.name)

    # # (4) 模糊查询
    # # __gt: 大于
    # # __lt: 小于
    # # __gte: 大于等于
    # # __lte: 小于等于
    # # __range[start,end]: 在...之间
    # # __in[list]: 在...之中
    # # __contains: 包含
    # # __startswith: 以...开头
    # # __endswith: 以...结尾
    # # 查询名称中包含"曾"的学生
    # students_like = await Student.filter(name__contains="曾") # QuerySet: [Student(),Student(),Student()]
    # print(students_like)

    # # (5) values查询
    # students_values = await Student.all().values("name") # QuerySet: [{'name': '张三'},{'name': '李四'},{'name': '王五'}]
    # print(students_values)

    # (6) 一对多查询 多对多查询
    stu = await Student.get(name='王艺超超')
    stu_classes = await stu.classes.values("name") 
    print(stu_classes) # {'name': '计算机科学与技术一班'}
    # students = await Student.all().values("name","classes__name")

    print(await stu.courses.all().values("name","teacher__name"))
    students = await Student.all().values("name","classes__name","courses__name","courses__teacher__name")
    return students

class StudentIn(BaseModel):
    name: str
    age: int
    gender: str
    create_time: datetime
    classes_id: int
    courses_id: list[int] = []

    @field_validator("name")
    def validate_name(cls, v):
        assert v.isalpha(), "name must be alphabetic"
        return v

@router.post("/")
async def create_student(student_in: StudentIn):

    # 插入到数据库
    # 方式1
    # student = Student(
    #     name=student_in.name,
    #     age=student_in.age,
    #     gender=student_in.gender,
    #     create_time=student_in.create_time,
    #     classes_id=student_in.classes_id,
    #     courses_id=student_in.courses_id
    # )
    # await student.save() # 保存到数据库Student表

    # 方式2 一般使用方式2
    student = await Student.create(
        name=student_in.name,
        age=student_in.age,
        gender=student_in.gender,
        create_time=student_in.create_time,
        classes_id=student_in.classes_id
    )
    # 多对多关系绑定
    choose_courses = await Course.filter(id__in=student_in.courses_id)
    await student.courses.add(*choose_courses)

    return student

@router.get("/{student_id}")
async def get_student(student_id: int):
    student = await Student.get(id=student_id)
    return student

@router.put("/{student_id}")
async def update_student(student_id: int,student_in: StudentIn):
    data = student_in.model_dump()
    courses = data.pop("courses")
    student = await Student.filter(id=student_id).update(**data)

    # 多对多关系绑定
    edit_stu = await Student.get(id=student_id)
    new_courses = await Course.filter(id__in=courses)
    edit_stu.courses.clear()
    await edit_stu.courses.add(*new_courses)

    return student

@router.delete("/{student_id}")
async def delete_student(student_id: int):
    deleteCount =  await Student.filter(id=student_id).delete() # 返回删除的数量
    if not deleteCount:
        raise HTTPException(status_code=404, detail=f"主键为{student_id}的学生不存在")

    return {}

